package plugins.test;

import com.bes.enterprise.web.jasper.tagplugins.jstl.core.Url;
import kd.bos.base.BaseShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.control.Image;
import kd.bos.form.control.Label;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.isc.util.dt.D;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import kd.sdk.plugin.Plugin;

import java.util.*;

/**
 * 动态表单插件
 */
public class test extends AbstractFormPlugin implements Plugin {

    // 存储菜品ID的列表，用于点击事件
    public List<String> dishIds = new ArrayList<>();



    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        loadRandomDishes();
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);

        // 为所有图片和标签控件注册点击监听器
        for (int i = 1; i <= 4; i++) {
            Image image = this.getView().getControl("dcb4_imageap1" + i);
            if (image != null) {
                image.addClickListener(this);
            }

            Label label = this.getView().getControl("dcb4_labelap2" + i);
            if (label != null) {
                label.addClickListener(this);
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);

        // this.getView().showMessage(String.valueOf(dishIds.size()));

        // 获取被点击的控件
        Control clickedControl = (Control) evt.getSource();
        String controlKey = clickedControl.getKey();

        // 确定点击的是哪个菜品（1-4）
        int dishIndex = getDishIndexFromControlKey(controlKey);
        if (dishIndex >= 0 && dishIndex < dishIds.size()) {
            // 获取对应菜品的ID
            String dishId = dishIds.get(dishIndex);
            openDishForm(dishId);
        }
    }

    private int getDishIndexFromControlKey(String controlKey) {
        // 从控件key中提取菜品索引（1-4）
        if (controlKey.startsWith("dcb4_imageap1") || controlKey.startsWith("dcb4_labelap2")) {
            String indexStr = controlKey.replace("dcb4_imageap1", "").replace("dcb4_labelap2", "");
            try {
                return Integer.parseInt(indexStr) - 1; // 转换为0-based索引
            } catch (NumberFormatException e) {
                return -1;
            }
        }
        return -1;
    }

    private void openDishForm(String dishId) {
        // 创建基础资料展示参数
        BaseShowParameter showParameter = new BaseShowParameter();
        showParameter.setFormId("dcb4_dishes"); // 基础资料表单ID
        showParameter.setPkId(dishId); // 设置要查看的菜品ID
        showParameter.getOpenStyle().setShowType(ShowType.Modal); // 模态框方式打开

        // 打开基础资料表单
        this.getView().showForm(showParameter);
    }

    private void loadRandomDishes() {
        dishIds.clear(); // 清空之前的ID列表

        String entityName = "dcb4_dishes";
        String selectFields = "dcb4_picture,name,id";

        // 获取所有菜品
        DynamicObject[] allDishes = BusinessDataServiceHelper.load(
                entityName, selectFields, new QFilter[0], "", Integer.MAX_VALUE
        );

        if (allDishes == null || allDishes.length == 0) {
            return;
        }

        // 随机选择4道菜品
        List<DynamicObject> randomDishes = new ArrayList<>(Arrays.asList(allDishes));
        Collections.shuffle(randomDishes);
        List<DynamicObject> selectedDishes = randomDishes.subList(0, Math.min(4, randomDishes.size()));

        // 显示随机选中的菜品
        int index = 0;
        for (DynamicObject dish : selectedDishes) {
            String picture = dish.getString("dcb4_picture");
            String name = dish.getString("name");
            String id = dish.getString("id");

            // 存储菜品ID
            dishIds.add(id);

            String imageFullUrl = UrlService.getImageFullUrl(picture);

            // 设置图片控件
            Image image = this.getView().getControl("dcb4_imageap1" + (index + 1));
            if (image != null) {
                image.setUrl(imageFullUrl);
                // image.setToolTip(name); // 添加提示信息
            }

            // 设置标签控件
            Label label = this.getView().getControl("dcb4_labelap2" + (index + 1));
            if (label != null) {
                label.setText(name);
                // label.setToolTip("点击查看详情"); // 添加提示信息
            }

            index++;
        }



        // this.getView().showMessage(String.valueOf(dishIds.size()));
    }
}
